package com.doyoo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doyoo.entity.JobStepTemplate;
import com.doyoo.enums.Type;
import com.doyoo.mapper.JobStepTemplateMapper;
import com.doyoo.service.JobStepTemplateService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class JobStepTemplateServiceImpl extends ServiceImpl<JobStepTemplateMapper, JobStepTemplate> implements JobStepTemplateService {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<JobStepTemplate> listAll(String type) {
        Type t = EnumUtils.getEnum(Type.class, type);
        LambdaQueryWrapper<JobStepTemplate> queryWrapper = Wrappers.<JobStepTemplate>lambdaQuery()
                .eq(StringUtils.isNotEmpty(type), JobStepTemplate::getType, EnumUtils.getEnum(Type.class, type));
        return list(queryWrapper);
    }

    @Override
    public String getCodes(Integer id, String templateParameter) throws JsonProcessingException {
        String script = getById(id).getScript();
        Map<String, String> parameterMap = (Map<String, String>)objectMapper.readValue(templateParameter, Map.class);
        String[] searchList = new String[parameterMap.keySet().size()];
        String[] replacementList = new String[parameterMap.keySet().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
            searchList[i] = "{{" + entry.getKey() + "}}";
            replacementList[i] = entry.getValue();
            i++;
        }
        String arg = StringUtils.replaceEachRepeatedly(script, searchList, replacementList);
        return arg;
    }
}
